import Vue from 'vue'
import router from '../router'
import lseapi from './api'
import lsedata from './data'
import lseloading from './loading'
let vue = new Vue()
// 基于 iview 组件
/**
 * 检查是否上传的是图片格式文件
 * {jpg , jpeg , png , gif} 区分大小写
 */
function checkFileIsImage (file, isBlob) {
  try {
    let fileName = file.name
    var suffixIndex = fileName.lastIndexOf('.')
    var src = window.URL.createObjectURL(isBlob ? new Blob(file) : file)
    var suffix = fileName.substring(suffixIndex + 1).toUpperCase()
    if (suffix !== 'JPG' && suffix !== 'JPEG' && suffix !== 'PNG' && suffix !== 'GIF' &&
      suffix !== 'jpg' && suffix !== 'jpeg' && suffix !== 'png' && suffix !== 'gif') {
      return false
    }
    return src
  } catch (error) {
    console.log(error)
    return false
  }
}

function checkUrlIsImg (url) {
  var suffixIndex = url.lastIndexOf('.')
  var suffix = url.substring(suffixIndex + 1).toUpperCase()
  if (suffix !== 'JPG' && suffix !== 'JPEG' && suffix !== 'PNG' && suffix !== 'GIF' &&
    suffix !== 'jpg' && suffix !== 'jpeg' && suffix !== 'png' && suffix !== 'gif') {
    return false
  }
  return true
}

function checkFileIsImageAndMp4 (file) {
  try {
    let fileName = file.name
    var suffixIndex = fileName.lastIndexOf('.')
    var src = window.URL.createObjectURL(file)
    var suffix = fileName.substring(suffixIndex + 1).toUpperCase()
    if (suffix !== 'JPG' && suffix !== 'JPEG' && suffix !== 'PNG' && suffix !== 'GIF' &&
      suffix !== 'jpg' && suffix !== 'jpeg' && suffix !== 'png' && suffix !== 'gif' && suffix !== 'mp4' && suffix !== 'MP4') {
      return false
    }
    return src
  } catch (error) {
    console.log(error)
    return false
  }
}

function checkFileIsAudio (file) {
  try {
    let fileName = file.name
    var suffixIndex = fileName.lastIndexOf('.')
    var src = window.URL.createObjectURL(file)
    var suffix = fileName.substring(suffixIndex + 1).toUpperCase()
    if (suffix !== 'mp3' && suffix !== 'MP3') {
      return false
    }
    return src
  } catch (error) {
    console.log(error)
    return false
  }
}

function checkFileIsVideo (file) {
  try {
    let fileName = file.name
    var suffixIndex = fileName.lastIndexOf('.')
    var src = window.URL.createObjectURL(file)
    var suffix = fileName.substring(suffixIndex + 1).toUpperCase()
    if (suffix !== 'mp4' && suffix !== 'MP4') {
      return false
    }
    return src
  } catch (error) {
    console.log(error)
    return false
  }
}

function checkFileIsExcel (file) {
  try {
    let fileName = file.name
    var suffixIndex = fileName.lastIndexOf('.')
    var src = window.URL.createObjectURL(file)
    var suffix = fileName.substring(suffixIndex + 1).toUpperCase()
    if (suffix !== 'XLS' && suffix !== 'XLSX') {
      return false
    }
    return src
  } catch (error) {
    console.log(error)
    return false
  }
}

function checkFileIsInTypes (file, types) {
  try {
    let fileName = file.name
    var suffixIndex = fileName.lastIndexOf('.')
    var src = window.URL.createObjectURL(file)
    var suffix = fileName.substring(suffixIndex + 1).toUpperCase()
    if (types.indexOf(suffix) === -1) {
      return false
    }
    return src
  } catch (error) {
    console.log(error)
    return false
  }
}

// z-index 需要在index.html中修改样式
function loading (text, type) {
  let load = lseloading.loading({
    msg: text,
    type: type || 3
  })
  return load
}

/**
 * 消息提醒 message
 * @param {*} data
 */
function msg (data = {}) {
  let config = {
    content: data.msg,
    duration: data.time || 3
  }
  switch (data.type) {
    case 1:
      vue.$Message.success(config)
      break
    case 2:
      vue.$Message.warning(config)
      break
    case 3:
      vue.$Message.error(config)
      break
    default:
      vue.$Message.info(config)
      break
  }
}

/**
 * alert 弹窗提醒
 * @param {*} msg
 * @param {*} data
 */
function alert (msg, data = {}) {
  data.title = data.title || '提示'
  let modal
  switch (data.type) {
    case 'info':
      modal = vue.$Modal.info({
        title: data.title,
        content: msg,
        okText: data.okText,
        onOk: data.onOk || function () {}
      })
      break
    case 'success':
      modal = vue.$Modal.success({
        title: data.title,
        content: msg,
        okText: data.okText,
        onOk: data.onOk || function () {}
      })
      break
    case 'warning':
      modal = vue.$Modal.warning({
        title: data.title,
        content: msg,
        okText: data.okText,
        onOk: data.onOk || function () {}
      })
      break
    case 'error':
      modal = vue.$Modal.error({
        title: data.title,
        content: msg,
        okText: data.okText,
        onOk: data.onOk || function () {}
      })
      break
    default:
      modal = vue.$Modal.confirm({
        title: data.title,
        content: msg,
        okText: data.okText,
        onOk: data.onOk || function () {},
        onCancel: data.onCancel || function () {}
      })
      break
  }
  return modal
}

/**
 * 右侧通知提醒
 * @param {*} data
 * data.info === '' 时 自动切换标题模式
 */
function notice (data = {}) {
  let title = data.title || '提示'
  switch (data.type) {
    case 1:
      vue.$Notice.success({
        title: title,
        desc: data.info || ''
      })
      break
    case 2:
      vue.$Notice.warning({
        title: title,
        desc: data.info || ''
      })
      break
    case 3:
      vue.$Notice.error({
        title: title,
        desc: data.info || ''
      })
      break
    case 4:
      vue.$Notice.open({
        title: title,
        desc: data.info || '',
        duration: 0,
        onClose: data.onClose
      })
      break
    default:
      vue.$Notice.info({
        title: title,
        desc: data.info || ''
      })
      break
  }
}

/**
 * 随机颜色
 */
function colorRandom () {
  let color = [
    'primary',
    'success',
    'magenta',
    'red',
    'volcano',
    'orange',
    'gold',
    'lime',
    'green',
    'cyan',
    'blue',
    'purple',
    '#FFA2D3'
  ]
  return color[parseInt(Math.random() * color.length)]
}

/**
 * 内部路由跳转
 * @param {*} path // 跳转位置（需要在router/index中配置路由）
 */
function goPath (path) {
  let token = lseapi.storageJson.get(lsedata.tokenName)
  console.log(token)
  if (token) {
    router.push({
      path: '/' + (path != null && path !== undefined ? path : '')
    })
  } else {
    msg({
      msg: '您当前未登录,无法进入'
    })
  }
}
function go (path) {
  router.push({
    path: '/' + (path != null && path !== undefined ? path : '')
  })
}
function goBack () {
  router.go(-1)
}

function objCopy (param) {
  let paramx = {}
  if (!param) {
    return ''
  }
  for (let par in param) {
    // console.log(par, typeof (param[par]))
    if (typeof (param[par]) === 'object' && (param[par] === null || param[par] === undefined || param[par].length === undefined)) {
      paramx[par] = objCopy(param[par])
    } else if (typeof (param[par]) === 'object' && param[par].length >= 0) {
      let array = arrayCopy(param[par])
      paramx[par] = array
    } else {
      paramx[par] = param[par]
    }
  }
  return paramx
}

function arrayCopy (array) {
  let arr = []
  array.forEach(item => {
    if (typeof (item) === 'object' && (item === null || item === undefined || item.length === undefined)) {
      arr.push(objCopy(item))
    } else if (typeof (item) === 'object' && item.length >= 0) {
      arr.push(arrayCopy(item))
    } else {
      arr.push(item)
    }
  })
  return arr
}

/**
 * 时间戳转换(13为时间戳)
 * @param timestamp
 * @returns {*}
 */
function timestampToTime (timestamp) {
  // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let date = new Date(timestamp)
  let Y = date.getFullYear() + '-'
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  let D = date.getDate() + ' '
  let h = date.getHours() + ':'
  let m = date.getMinutes() + ':'
  let s = date.getSeconds()
  return Y + M + D + h + m + s
}

/**
 * 倒计时
 * @param {*} sec
 */
function countdown (sec) {
  if (sec <= 0) {
    return
  }
  console.log(sec)
  setTimeout(() => {
    sec = sec - 1
    countdown(sec)
  }, 1000)
}

/**
 * 根据数据列拆分行内数据
 * @param {每行多少个card} n
 * @param {数据列} dataList
 * @returns
 */
function getDivList (n, dataList) {
  let list = []
  list.push({
    type: 'refresh'
  })
  dataList.forEach(item => {
    list.push(item)
  })
  list.push({
    type: 'add'
  })
  let divList = []
  let datas = []
  let size = parseInt(Math.ceil(list.length / n))
  for (let s = 0; s < size; s++) {
    let length = s * n + n
    length = length > list.length - 1 ? list.length : length
    for (let i = s * n; i < length; i++) {
      datas.push(list[i])
    }
    divList.push(datas)
    datas = []
  }
  return divList
}

/**
 * 根据数据列拆分行内数据
 */
function splitList (n, dataList) {
  let list = []
  dataList.forEach(item => {
    list.push(item)
  })
  let divList = []
  let datas = []
  let size = parseInt(Math.ceil(list.length / n))
  for (let s = 0; s < size; s++) {
    let length = s * n + n
    length = length > list.length - 1 ? list.length : length
    for (let i = s * n; i < length; i++) {
      datas.push(list[i])
    }
    divList.push(datas)
    datas = []
  }
  return divList
}

function getGroupField (rows) {
  let form = {}
  rows.forEach(row => {
    row.forEach(col => {
      col.forEach(ele => {
        if (ele.config.field) {
          form[ele.config.field] = ele.config.default
        }
      })
    })
  })
  return form
}

let formTypeMap = {
  text: 'string',
  input: 'string',
  select: 'string',
  switch: 'string',
  radio: 'string',
  checkbox: 'string'
}

function getGroupFieldDatas (rows) {
  let form = {}
  rows.forEach(row => {
    row.forEach(col => {
      col.forEach(ele => {
        if (ele.config.field) {
          // console.log(ele)
          let config = ele.config
          form[ele.config.field] = [config.default, (config.tableLabel || config.field), config.label, formTypeMap[config.eleType] || config.eleType]
        }
      })
    })
  })
  return form
}

function createTableTem (html, row) {
  // console.log(html, row)
  const vm = new (Vue.extend({
    template: `<div>${html}</div>`,
    data () {
      return {
        row: row
      }
    }
  }))().$mount()
  return vm.$el.outerHTML
}

export default {
  checkFileIsImage,
  loading,
  msg,
  goPath,
  go,
  timestampToTime,
  goBack,
  checkFileIsImageAndMp4,
  prompt,
  confirm,
  checkUrlIsImg,
  alert,
  notice,
  colorRandom,
  objCopy,
  arrayCopy,
  countdown,
  checkFileIsExcel,
  getDivList,
  checkFileIsVideo,
  checkFileIsAudio,
  checkFileIsInTypes,
  splitList,
  getGroupField,
  getGroupFieldDatas,
  createTableTem
}
